var uploader;
/***
 * 百度webuploader调用封装
 * @author 卢永华 2015-02-05
 * @param url 访问链接
 * @param num 上传文件数量限制，默认值：5
 * @param size 上传文件大小限制，默认值：200MB，设定值：1MB以上
 * @param accept 上传文件类型限制，默认为图片类型
 * @param params 发送参数
 */
var iuploader=function(url,num,size,accept,pick,uploaderList,params){
	num=num==null?1:parseInt(num);
	size=size==null?200:size;
	
	var limit_size_=size;
	if(!pick){
		var pick="#picker";
	}
	if(!uploaderList){
		var uploaderList="#thelist";
	}
	if(!params){
		var params={};	
	}
	if(!accept){
		var accept={
			title: 'Applications',
			extensions: 'doc,pdf,xls,jpeg,jpg,jpe,png,bmp,gif,xlsx,xls,xlb,xlt,xltx,docx,dotx,zip,ppt,pps,pot,pptx',
			mimeTypes: 'application/msword,application/pdf,application/vnd.ms-excel,image/jpeg,image/jpeg,image/jpeg,image/png,image/bmp,image/gif,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,application/vnd.ms-excel,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/zip,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation'
		};
	}
 	var $ = jQuery,
    	$list = $(uploaderList),
    	$btn = $('#ctlBtn'),
    	state = 'pending', 
    	$disBtn=$('.btn-primary');
   // var uploadSize=$list.find('.item').length;
 	uploader = WebUploader.create({
	    // swf文件路径
	    swf: BASE_URL+'/webuploader/Uploader.swf',
	    // 文件接收服务端。
	    server:url,
	    // 选择文件的按钮。可选。
	    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
	    pick: pick,
	    // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
	    resize: false,
	    auto: true,
	    formData:params,
	    fileNumLimit:num,
	    fileSingleSizeLimit:(size*1024*1024),
	    //uploadedFileSize:2,
	    accept:accept
	});
 	//开始上传文件
 	uploader.on('uploadStart',function(file){
 		if($disBtn){
 			$disBtn.attr('disabled',true);
 		}
		loading("\u6b63\u5728\u4fdd\u5b58\u9644\u4ef6\uff0c\u8bf7\u7a0d\u7b49...");//正在保存附件，请稍等
	});
 	
 	uploader.on('uploadSuccess', function(file, response){
 		closeLoading();
 		
 		if($disBtn){
 			$disBtn.attr('disabled',false);
 		}
 		
 		var fileId = file.id;
 		$('#' + file.id + '_dm').val(response.id);
 		$('#' + file.id + " .state").html("\u5b8c\u6210");
 		
 	});
 	
 	//文件上传失败
	uploader.on('uploadError',function(file,reason){
		closeLoading();
		if($disBtn&&$disBtn.attr('disabled')){
 			$disBtn.removeAttr('disabled',true);
 		}
		alertx("\u4fdd\u5b58\u9644\u4ef6\u5931\u8d25\uff01");//保存附件失败！
	});
	// 当有文件被添加进队列的时候
	uploader.on( 'fileQueued', function( file ) {
		var $hasFile=$list.find('.item');
	   // console.log(file.id);
	    if($hasFile.length===num){
	    	alert('\u5df2\u8fbe\u5230\u4e0a\u4f20\u6570\u91cf\u9650\u5236\uff01');//已达到上传数量限制！
	    	return;
	    }
	    //\u5220\u9664-->删除
	    $list.append( '<div id="' + file.id + '" class="item">' +
	        '<h4 class="info"><a class="info" id="'+file.id+'_xz" href="javascript:void(0);" onclick="downloadFile (\''+file.id+'\')">' + file.name +'</a>'+
	       // '<input  onclick="downloadFile (\''+file.id+'\')" class="btn btn-xs btn-primary" style="display:none" type="button" value="下载">'+
	       // '<a class="btn btn-xs btn-primary" href="javascript:void(0);" id="'+file.id+'_xz" style="display:none" >下载</a>' +
	        '<input id="'+file.id+'_del" onclick="delFile(\''+file.id+'\')" class="btn btn-xs btn-danger" type="button" value="\u5220\u9664" /></h4>'+
	        '<input id="'+file.id+'_dm" type="hidden"/>'+
	        '<p class="state"></p>' +
	    '</div>' );
	});
	
	// 文件上传过程中创建进度条实时显示。
	uploader.on('uploadProgress', function( file, percentage ) {
	    var $li = $( '#'+file.id ),
	        $percent = $li.find('.progress .progress-bar');
	
	    // 避免重复创建
	    if ( !$percent.length ) {
	        $percent = $('<div class="progress progress-striped active">' +
	          '<div class="progress-bar" role="progressbar" style="width: 0%">' +
	          '</div>' +
	        '</div>').appendTo( $li ).find('.progress-bar');
	    }
	
	    $li.find('p.state').text('\u4e0a\u4f20\u4e2d');//上传中
	
	    $percent.css( 'width', percentage * 100 + '%' );
	});
	
	uploader.on( 'uploadError', function( file ) {
	    $('#'+file.id ).find('p.state').text('\u4e0a\u4f20\u51fa\u9519');//上传出错
	});
	
	uploader.on( 'uploadComplete', function( file ) {
	    $('#'+file.id ).find('.progress').fadeOut();
	});
	uploader.on( 'all', function( type ) {
        if ( type === 'startUpload' ) {
            state = 'uploading';
        } else if ( type === 'stopUpload' ) {
            state = 'paused';
        } else if ( type === 'uploadFinished' ) {
            state = 'done';
        }

        if ( state === 'uploading' ) {
            $btn.val('\u6682\u505c\u4e0a\u4f20');//暂停上传
        } else {
            $btn.val('\u5f00\u59cb\u4e0a\u4f20');//开始上传
        }
    });
	uploader.on('error',function(type){
		if(type==='Q_EXCEED_NUM_LIMIT'){
			alert('\u6700\u591a\u53ea\u5141\u8bb8\u4e0a\u4f20'+num+'\u4e2a\u6587\u4ef6');//最多只允许上传N个文件
		}
		if(type==='F_EXCEED_SIZE'){
			alert('\u5141\u8bb8\u4e0a\u4f20\u6587\u4ef6\u7684\u5927\u5c0f\u4e3a'+limit_size_+'MB,\u8bf7\u538b\u7f29\u540e\u518d\u4e0a\u4f20\uff01');//允许上传文件的大小为xxMB,请压缩后再上传！
		}
	});
	$btn.on( 'click', function() {
        if ( state === 'uploading' ) {
            uploader.stop();
        } else {
            uploader.upload();
        }
    });
	
    return uploader;
};

function removeFile(id){
	var file=uploader.getFile(id);
	if(file){
		uploader.removeFile(file);
	}
}

function delFile2(id,attachment){
	var uploaded=$('#'+id+'_dm').val();
	if(uploaded!=''&&uploaded!=null){
		if(!deleteF(uploaded, fileId)){
			return;
		}
	}
	//removeFile(id);
	if(attachment!=undefined){
		var temp=$('#'+attachment);
		temp.val(temp.val().replace(uploaded,''));
	}
	//$('#'+id).remove();
}
function delFile(id){
	
	layer.confirm('要删除附件吗？', {icon: 3, title:'提示'}, function(index){
		
		var uploaded=$('#'+id+'_dm').val();
		if(uploaded!=''&&uploaded!=null){
			if(!deleteF(uploaded, id)){
				return;
			}
		}
		//removeFile(id);
		//$('#'+id).remove();
		
		layer.close(index);
		window.location.href=url;
	});
	
}
function deleteF(id, fileId){
	var result=false;
	loading("\u6b63\u5728\u5220\u9664\u9644\u4ef6\uff0c\u8bf7\u7a0d\u7b49...");//正在删除附件，请稍等
	$.ajax({
		url:ctx+"/oa/oaNotify/deleteFile.do",
		type:'post',
		dataType:'text',
		data:{id:id},
		async: false,
		success:function(res){
			closeLoading();
			if(res=='success' || res == ''){
				result=true;
				removeFile(fileId);
				
				$('#'+fileId).remove();
				
			}else{
				layer.msg(res);
			}
		},
		error: function (jqXHR, textStatus, errorThrown) {
			closeLoading();
			layer.msg("系统错误，请联系开发商！");
        }
	});
	return result;
}

function downloadFile(id){
	var fileId=$('#'+id+'_dm').val();
	if(fileId==""){
		return false;
	}
	window.location.href=ctx+"/oa/oaNotify/downloadFile.do?id="+fileId+"&random="+Math.random();
}

function downloadFile2(id){
	window.location.href=ctx+"/oa/oaNotify/downloadFile.do?id="+id+"&random="+Math.random();
}

